package NewTmas.EditMode;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: abhatnag
 * Date: 8/15/11
 * Time: 10:10 AM
 * To change this template use File | Settings | File Templates.
 */
public class ApplyGraphChangesListener implements ActionListener
{

    List<EditStep> editStepList;
    EditIntFrame editIntFrame;


    public ApplyGraphChangesListener(List<EditStep> sqlCommands, EditIntFrame e)
    {
        this.editStepList = sqlCommands;
        this.editIntFrame = e;
    }

    public void actionPerformed(ActionEvent e)
    {
        for (EditStep entry : editStepList)
        {
            try
            {
                System.out.println("going to execute " + entry);
                entry.exec();
            } catch (SQLException e1)
            {
                e1.printStackTrace();
                JOptionPane.showConfirmDialog(null, "Could not execute Step Due to: " + e1.getMessage(), "Error", JOptionPane.DEFAULT_OPTION);
                try { editIntFrame.user.getConnection().rollback(); } catch (SQLException e2) { e2.printStackTrace(); }
                return;
            }
        }

        final boolean commit = editIntFrame.commitCBox.isSelected();
        editIntFrame.refreshAndRedrawGraph(commit);
        if (commit)
        {
            try
            {
                editIntFrame.user.getConnection().commit();
                editIntFrame.sqlCommands.clear();
                editIntFrame.model.removeAllElements();
                editIntFrame.model.clear();
                editIntFrame.commitCBox.setSelected(false);
            } catch (SQLException e1)
            {
                e1.printStackTrace();
                JOptionPane.showConfirmDialog(null, "Could not commit due to: " + e1.getMessage(), "Error", JOptionPane.DEFAULT_OPTION);
            }
        } else
        {
            try
            {
                editIntFrame.user.getConnection().rollback();
            } catch (SQLException e1)
            {
                JOptionPane.showConfirmDialog(null, "Could not rollback due to: " + e1.getMessage(), "Error", JOptionPane.DEFAULT_OPTION);
            }
        }
    }

}
